<?php
    require('common.php');
        
    $db = new Database();
    
    if(!isset($_POST['user']) || !isset($_POST['password']) || 
       !isset($_POST['realname']) || !isset($_POST['repassword']))
        throw new Exception('Bad request.');
    
    // Check that there isn't another user with the same name
    $result = $db->query('SELECT id FROM '.
        config('DB_PREFIX').'users WHERE name='.
        $db->escape( $_POST['user'] ) );
    if(mysqli_num_rows($result) > 0) {
        message(LANG('USERNAME_TAKEN'), 
            'javascript: history.go(-1);',
            lang('BACK_TO_SIGNUP'));
        exit();
    }
    
    // Check that password=repassword
    if( $_POST['password'] != $_POST['repassword'] ) {
        message(LANG('PASSWORD_MISMATCH'), 
            'javascript: history.go(-1);',
            lang('BACK_TO_SIGNUP'));
        exit();
    }
    // Create the user
    $salt = generateSalt();
    $db->query('INSERT INTO '.config('DB_PREFIX').'users '.
        '(name, salt, password, group_id, real_name) VALUES ('.
        $db->escape($_POST['user']).', '.
        '\''.$salt.'\', '.
        '\''.sha1($salt.$_POST['password']).'\', '.
        '1, '.
        $db->escape($_POST['realname']).')');
    
    // Success
    redirect('login.php');
?>